package com.icangya.weixin;

import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.IUserFootDAO;
import com.icangya.Utils.*;
import com.icangya.Value.StaticValue;
import com.icangya.domain.*;
import com.icangya.service.IDomainService;
import com.icangya.service.IFootUserService;
import com.icangya.service.IMissionService;
import com.icangya.service.IMoneyService;
import com.icangya.weixin.sdk.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 王小红 on 2017/5/15.
 * 接受微信
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/wechat/")
public class WechatController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private ImageUtils imageUtils = ImageUtils.getIstance();
    private WeixinUtil weixinUtil = WeixinUtil.getIstance();
    private DESUtil desUtil = DESUtil.getIstance();

    @Autowired
    private IFootUserService iUserService;
    @Autowired
    private IMoneyService iMoneyService;
    @Autowired
    private IMissionService iMissionService;
    @Autowired
    private IDomainService iDomainService;

    //微信请求的URL=https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http://ssc.yipapa
    // .com/qqonline/wechat/loginCallBack?
    // &response_type=code&scope=SCOPE&state=STATE#wechat_redirect
//    @RequestMapping(value = "loginCallBack")
//    public void loginCallBack(@RequestParam String code, @RequestParam String state, Long parentID, Long proxyID,
//                              HttpServletResponse response,HttpSession session) throws Exception {
//        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
//        logger.info("WX.REAL_GAME_URL:"+WX.REAL_GAME_URL);
//        logger.info("======code=" + code + " state=" + state + " parentID=" + parentID);
//
//        if (parentID == null)
//            parentID = 0L;//若无则是系统
//        if (proxyID == null)
//            proxyID = 1L;//若无则是admin
//
//        logger.info("appid:"+WX.AppId+"===appsecret:"+WX.AppSecret);
//        OAuthAccessToken accessToken = weixinUtil.getOAuthAccessToken(WX.AppId, WX.AppSecret, code);
//
//        accessToken = weixinUtil.refershOAuthAccessToken(WX.AppId, accessToken.getRefreshToken());//刷新accessTokenn
//        String openID = accessToken.getOpenid();
//
//        org.json.JSONObject userjson = weixinUtil.acceptOAuthUserNews(accessToken.getAccessToken(),openID);
//
//        User user = iUserService.getByOpenId(openID);
//
//        if (user == null) {//用户不存在//做注册
//            /*构建用户start*/
//            User userDO = new User();
//            userDO.setNickName(userjson.getString("nickname"));
//            userDO.setHeadImgUrl(userjson.getString("headimgurl"));
////            userDO.setShield((byte) 0);
//            userDO.setOpenId(openID);
//            userDO.setParentId(parentID);
//            userDO.setProxyId(proxyID);
////            userDO.setModifiedTime(now);
//            userDO.setCreateTime(now);
////            userDO.setRemark("");
//            /*构建用户end*/
//            user = iUserService.addUser(userDO);//注册进去
//            System.out.println("user.getId():{"+user.getId());
//
//            /*创建用户的余额和佣金表start*/
//            Balance balance=new Balance();//广告金
//            balance.setCreateTime(now);
//            balance.setModifiedTime(now);
//            balance.setMoney(0.0);
//            balance.setOpenId(user.getOpenId());
//
//            Commission commission=new Commission();//佣金
//            commission.setCreateTime(now);
//            commission.setModifiedTime(now);
//            commission.setMoney(0.0);
//            commission.setOpenId(user.getOpenId());
//            iMoneyService.saveBalance(balance);
//            iMoneyService.saveCommission(commission);
//            /*创建用户的余额和佣金表end*/
//
//            /*创建用户的赠送广告金表start*/
//            GiftAdvertMoney giftAdvertMoney =new GiftAdvertMoney();//广告金
//            giftAdvertMoney.setOpenId(openID);
//            giftAdvertMoney.setCreateTime(now);
//            giftAdvertMoney.setModifiedTime(now);
//            giftAdvertMoney.setGitAdvertMoney(0.0);
//            iMoneyService.saveGiftAdvertMoney(giftAdvertMoney);
//            /*创建用户的赠送广告金表end*/
//
//
//            /**生成二维码start*/
//            final long uid = user.getId();
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    logger.info("===========uid:"+uid+"============6564654==============================");
//                    User needQR = iUserService.getUserByUid(uid);
//                    String shareUrl = null;
//                    try {
//                        shareUrl = WX.ShareUrl.replace("APPID", WX.AppId).replace("REDIRECT_URI", URLEncoder.encode(
//                                WX.GAME_URL + "parentID=" + needQR.getId() + "&proxyID=" + needQR.getProxyId(),
//                                "UTF-8")).replace("SCOPE", WX.HAVE_USER_INFO_SCOPE);
//                        logger.info("shareUrl : " + shareUrl);
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }
//                    logger.info("这是测试登录:  QRCode=" + shareUrl);
//                    String SB = imageUtils.GetQR_BASE64(shareUrl);
////                    logger.info(SB);
//                    needQR.setQrCode(SB);
//                    iUserService.updateUser(needQR);//更新一下二维码图片 完成注册操作
//                }
//            }).start();
//            /**生成二维码end*/
//            /**生成上下级关系表start*/
//            ProxyLevel proxyLevelDO;
//            if (parentID == 0L) {
//                proxyLevelDO = new ProxyLevel(user.getId(),openID, 0L, 0L, 0L, 0L);
//            } else {
//                proxyLevelDO = iUserService.getProxyLevel(parentID);
//                proxyLevelDO = new ProxyLevel(user.getId(),openID, proxyLevelDO.getUid(), proxyLevelDO.getFirstLevel(),
//                        proxyLevelDO.getSecondLevel(), proxyLevelDO.getThirdLevel());
//            }
//            iUserService.saveProxyLevel(proxyLevelDO);
//            /**生成上下级关系表end*/
//        }//完成注册
//        /**MD5加密start*/
//        System.out.println("user.getId():{"+user.getId());
//        String md5Str = "uid=" + user.getId() + "&cy_key=" + StaticValue.SIGN_KEY;//原文   uid=UID&cy_key=CY_KEY
//        md5Str = DigestUtils.md5DigestAsHex(md5Str.getBytes("UTF-8"));//md5加密一次
//        md5Str = DigestUtils.md5DigestAsHex(md5Str.getBytes("UTF-8"));//md5加密二次  需要DES再加密
//        /**MD5加密end*/
//        /**DES加密start*/
//        int size = md5Str.getBytes().length;
//        size = size % 8;
//        for (int i = 0; i < size; i++) {//做成8的倍数才能加密
//            md5Str += " ";
//        }
//        String desStr = desUtil.encrypt(md5Str, StaticValue.SIGN_KEY);//DES用key来加密           加密后的密文
//        /**DES加密over*/
//        desStr = URLEncoder.encode(desStr, "UTF-8");//url编码
//        desStr = "uid=" + user.getId() + "&cy_key=" + desStr;
////        if (user.getShield().equals((byte) 0)) {//是会员哦
//            response.sendRedirect(WX.REAL_GAME_URL + desStr);//转入二级域名  游戏用域名
////        }else {
////            response.sendRedirect(StaticValue.ERROR_URI);//屏蔽
////        }
//    }



    @RequestMapping(value = "testloginCallBack")
    public void testloginCallBack(String openID,String nickname,String headimgurl, Long parentID, Long proxyID, HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
//        logger.info("WX.REAL_GAME_URL:"+WX.REAL_GAME_URL);

        nickname = URLDecoder.decode(nickname,"UTF-8");
        logger.info(nickname+"===============================================================================");

        if (parentID == null)
            parentID = 0L;//若无则是系统
        if (proxyID == null)
            proxyID = 1L;//若无则是admin

        User user = iUserService.getByOpenId(openID);

        if (user == null) {//用户不存在//做注册
            /*构建用户start*/
            User userDO = new User();
            userDO.setNickName(nickname);
            userDO.setHeadImgUrl(headimgurl);
//            userDO.setShield((byte) 0);
            userDO.setOpenId(openID);
            userDO.setParentId(parentID);
            userDO.setProxyId(proxyID);
//            userDO.setModifiedTime(now);
            userDO.setCreateTime(now);
//            userDO.setRemark("");
            /*构建用户end*/
            try {
                user = iUserService.addUser(userDO);//注册进去
            }catch (Exception e){
                logger.info("用户信息添加出现异常："+e.getMessage());
                userDO.setNickName("nick_name");
                user = iUserService.addUser(userDO);//注册进去
            }

            logger.info("user.getId():{"+user.getId());

            /*创建用户的余额和佣金表start*/
            Balance balance=new Balance();//广告金
            balance.setCreateTime(now);
            balance.setModifiedTime(now);
            balance.setMoney(0.0);
            balance.setOpenId(user.getOpenId());

            Commission commission=new Commission();//佣金
            commission.setCreateTime(now);
            commission.setModifiedTime(now);
            commission.setMoney(0.0);
            commission.setOpenId(user.getOpenId());
            iMoneyService.saveBalance(balance);
            iMoneyService.saveCommission(commission);
            /*创建用户的余额和佣金表end*/

            /*创建用户的赠送广告金表start*/
            GiftAdvertMoney giftAdvertMoney =new GiftAdvertMoney();//广告金
            giftAdvertMoney.setOpenId(openID);
            giftAdvertMoney.setCreateTime(now);
            giftAdvertMoney.setModifiedTime(now);
            giftAdvertMoney.setGitAdvertMoney(0.0);
            iMoneyService.saveGiftAdvertMoney(giftAdvertMoney);
            /*创建用户的赠送广告金表end*/

            /**生成二维码start*/
            final long uid = user.getId();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    logger.info("===========uid:"+uid+"============生成二维码==============================");
                    User needQR = iUserService.getUserByUid(uid);
                    String shareUrl = null;
                    try {
//                        shareUrl = WX.ShareUrl.replace("APPID", WX.AppId).replace("REDIRECT_URI", URLEncoder.encode(WX.CENTER_URL + "parentID=" + needQR.getId() + "&proxyID=" + needQR.getProxyId(),
//                                "UTF-8")).replace("SCOPE", WX.HAVE_USER_INFO_SCOPE);
                        shareUrl = StaticValue.WX.ENTER_URL+"parentID=" + needQR.getId() + "&proxyID=" + needQR.getProxyId();

                        logger.info("shareUrl : " + shareUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("这是测试登录:  QRCode=" + shareUrl);
                    String SB = imageUtils.GetQR_BASE64(shareUrl);
                    needQR.setQrCode(SB);
                    iUserService.updateUser(needQR);//更新一下二维码图片 完成注册操作
                }
            }).start();
            /**生成二维码end*/
            /**生成上下级关系表start*/
            ProxyLevel proxyLevelDO;
            if (parentID == 0L) {
                proxyLevelDO = new ProxyLevel(user.getId(),openID, 0L, 0L, 0L, 0L);
            } else {
                proxyLevelDO = iUserService.getProxyLevel(parentID);
                proxyLevelDO = new ProxyLevel(user.getId(),openID, proxyLevelDO.getUid(), proxyLevelDO.getFirstLevel(),
                        proxyLevelDO.getSecondLevel(), proxyLevelDO.getThirdLevel());
            }
            iUserService.saveProxyLevel(proxyLevelDO);
            /**生成上下级关系表end*/
        }//完成注册
        /**MD5加密start*/
        logger.info("user.getId():{"+user.getId());
        String md5Str = "uid=" + user.getId() + "&cy_key=" + StaticValue.SIGN_KEY;//原文   uid=UID&cy_key=CY_KEY
        md5Str = DigestUtils.md5DigestAsHex(md5Str.getBytes("UTF-8"));//md5加密一次
        md5Str = DigestUtils.md5DigestAsHex(md5Str.getBytes("UTF-8"));//md5加密二次  需要DES再加密
        /**MD5加密end*/
        /**DES加密start*/
        int size = md5Str.getBytes().length;
        size = size % 8;
        for (int i = 0; i < size; i++) {//做成8的倍数才能加密
            md5Str += " ";
        }
        String desStr = desUtil.encrypt(md5Str, StaticValue.SIGN_KEY);//DES用key来加密           加密后的密文
        /**DES加密over*/
        desStr = URLEncoder.encode(desStr, "UTF-8");//url编码
        desStr = "uid=" + user.getId() + "&cy_key=" + desStr;
//        if (user.getShield().equals((byte) 0)) {//是会员哦
//        response.sendRedirect(WX.REAL_GAME_URL + desStr);//转入二级域名  游戏用域名
        response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl()+"/foot/user/loginGame?" + desStr);//转入二级域名  游戏用域名

//        }else {
//            response.sendRedirect(StaticValue.ERROR_URI);//屏蔽
//        }
    }

    @RequestMapping(value = "getweixinjs")
    public JSONObject getweixinjs(HttpSession session,@RequestParam String url){

        HashMap<String,String> hm = new HashMap<>();
        try {
           hm = JSSDK_Config.jsSDK_Sign(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("=====================JSONObject.toJSON(hm)======================");
        System.out.print(JSONObject.toJSON(hm));
        return JSONUtils.getRoot(0,"success",JSONObject.toJSON(hm));

    }

    /**
     * 游戏币购买接口
     * @param money
     * @param openid
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "shoppay",method = RequestMethod.POST)
    public JSONObject shoppay(@RequestParam String money,@RequestParam String openid, HttpServletRequest request,HttpSession session){

        int realmoney = 500;

        switch (money){
            case "1" :
                realmoney = 500;
                break;
            case "2" :
                realmoney = 1000;
                break;
            case "3" :
                realmoney = 5000;
                break;
            case "4" :
                realmoney = 50000;
                break;
            case "5" :
                realmoney = 100000;
                break;
            case "6" :
                realmoney = 200000;
                break;
            default:realmoney = 200000;
                break;
        }

        MyConfig config = null;
        try {
            config = new MyConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        User user = (User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String timeStamp = String.valueOf(new Date().getTime());

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "充值");
        data.put("out_trade_no", WXPayUtil.generateUUID());
        data.put("device_info", "WEB");
        data.put("openid",openid);
        data.put("fee_type", "CNY");
        data.put("total_fee", String.valueOf(realmoney));
//        data.put("spbill_create_ip", CusAccessObjectUtil.getIpAddress(request));
        data.put("spbill_create_ip", "192.168.0.1");

        try {
            data.put("notify_url", StaticValue.WX.BASE_URL+ "/foot/user/weixinpay/callback");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        data.put("product_id", "fb"+WXPayUtil.generateUUID());


        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);

            Map<String, String> data2 = new HashMap<String, String>();
            data2.put("appId", StaticValue.WX.AppId);
            data2.put("timeStamp", timeStamp);
            data2.put("nonceStr", WXPayUtil.generateUUID());
            data2.put("package","prepay_id="+resp.get("prepay_id"));
            data2.put("signType", "MD5");
            String paySign = WXPayUtil.generateSignature(data2,config.getKey());
            data2.put("paySign",paySign);
            logger.info("=====================data2======================");
            System.out.println(data2);


            return JSONUtils.getRoot(0,"success",data2);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONUtils.getRoot(1,"faild","");
        }
    }



    /**
     * 商品订单购买接口
     * @param openid
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "orderpay",method = RequestMethod.POST)
    public JSONObject orderpay(@RequestParam String openid, @RequestParam String generateUUID, HttpServletRequest request,HttpSession session){

//        int realmoney = 500;
//
//        switch (money){
//            case "1" :
//                realmoney = 500;
//                break;
//            case "2" :
//                realmoney = 1000;
//                break;
//            case "3" :
//                realmoney = 5000;
//                break;
//            case "4" :
//                realmoney = 50000;
//                break;
//            case "5" :
//                realmoney = 100000;
//                break;
//            case "6" :
//                realmoney = 200000;
//                break;
//            default:realmoney = 200000;
//                break;
//        }
        //此处金额以查询数据库表订单的金额为准
        //系统数据库处理逻辑（待修改）
        FbOrder fbOrder = iMissionService.getOrderByOutTrantId(generateUUID);
        String money = String.valueOf(fbOrder.getOrderMoney() * 100);
        logger.info("支付操作==用户："+fbOrder.getNickName()+"的订单："+generateUUID+"总金额为："+money);

        MyConfig config = null;
        try {
            config = new MyConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        WXPay wxpay = null;
        try {
            wxpay = new WXPay(config);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        User user = (User)session.getAttribute(FootBall.FOOT_USER_SESSION);
        String timeStamp = String.valueOf(new Date().getTime());

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "订单");
        data.put("out_trade_no", generateUUID);
        data.put("device_info", "WEB");
        data.put("openid",openid);
        data.put("fee_type", "CNY");
        data.put("total_fee", money);
//        data.put("spbill_create_ip", CusAccessObjectUtil.getIpAddress(request));
        data.put("spbill_create_ip", "192.168.0.1");

        try {
            //订单回调地址
            data.put("notify_url", StaticValue.WX.BASE_URL+ "/foot/user/weixinpay/callback");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        data.put("product_id", "fb"+WXPayUtil.generateUUID());


        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);

            Map<String, String> data2 = new HashMap<String, String>();
            data2.put("appId", StaticValue.WX.AppId);
            data2.put("timeStamp", timeStamp);
            data2.put("nonceStr", WXPayUtil.generateUUID());
            data2.put("package","prepay_id="+resp.get("prepay_id"));
            data2.put("signType", "MD5");
            String paySign = WXPayUtil.generateSignature(data2,config.getKey());
            data2.put("paySign",paySign);
            logger.info("=====================data2======================");
            System.out.println(data2);


            return JSONUtils.getRoot(0,"success",data2);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONUtils.getRoot(1,"faild","");
        }
    }
}